package com.springboot.springbootmybatisannotation.intercepter;


import com.alibaba.fastjson.JSON;
import com.springboot.springbootmybatisannotation.utils.StringUtils;
import com.springboot.springbootmybatisannotation.utils.ObjUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;


@Configuration
@Slf4j
@Aspect
public class ControllerLevelAopIntercepter {

  private static final Logger LOGGER = LoggerFactory.getLogger(ControllerLevelAopIntercepter.class);

  @Pointcut("execution(public * com.springboot.springbootmybatisannotation.controller..*.*(..))")
  public void controllerAspect() {
  }

  @Around("controllerAspect()")
  public Object handlerControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
    long startTime = System.currentTimeMillis();

    // 调用方法
    String callMethod =
      pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName();

    String uuid = UUID.randomUUID().toString();
    // 记录请求日志
    saveRequestLog(pjp, callMethod, uuid);

    // 执行方法
    Object result = pjp.proceed();

   /* LOGGER.info(
      uuid + ":请求已完成方法 :【" + callMethod + "】, 返回值: 【" + JSON.toJSONString((null) )
        + "】");*/
    LOGGER.info(
      uuid + ":请求已完成方法:【" + callMethod + "】, 耗时: 【" + (System.currentTimeMillis() - startTime)
        + " ms 】");
    return result;
  }

  private void saveRequestLog(ProceedingJoinPoint pjp, String callMethod, String uuid) {
    HttpServletRequest request = currentRequest();
    if (request != null) {
      LOGGER.info(uuid + ":请求方法 :【" + callMethod + "】,请求参数 :【 " + (JSON.toJSONString(pjp.getArgs()))
        + "】,请求地址 : 【"
        + request.getRequestURL().toString() + "】, 客户端 IP:【" + request.getRemoteAddr() + "】");
    }
  }

  public static HttpServletRequest currentRequest() {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
      .currentRequestAttributes();
    return attributes.getRequest();
  }


  /**
   * 获得当前请求中的cityId
   *
   * @return
   */
  public static String currentStaff() {
    String cityId = StringUtils.EMPTY;
    HttpServletRequest httpServletRequest = currentRequest();
    if (ObjUtils.isNotEmpty(httpServletRequest)) {
       cityId = httpServletRequest.getHeader("cityId");
       if(ObjUtils.isNotEmpty(cityId)){
         log.info("获取的cityId为：=====》{}", cityId);
       }
    }
    return cityId;
  }

}
